<?php 

namespace Home\Controller;

use Api\Event\Sso\ISso;
use Api\Event\UserEvent;
use Common\Util\ThinkSDK\ThinkOauth;
use Think\Log;
use Think\Exception;

// +----------------------------------------------------------------------
// | 文件 SsoController.class.php
// +----------------------------------------------------------------------
// | 说明 第三方授权相关
// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
// | Author: 谢赤心 Legend. <xcx_legender@qq.com>
// +----------------------------------------------------------------------

class SsoController extends HomeController {

    public function code()
    {
        $channel = I('channel');
        $this->code = $code = I('code');
        if (!$channel){
            return $this->showError();
        }
        $redirect_url = I('redirect_url', U('Index/index'));
        $sns = ThinkOauth::getInstance($channel);
        try {
            $extend = $sns->parseExtend(I(''));
            $open = $sns->getAccessToken($code, $extend);
        } catch (\Exception $e) {
            \Think\Log::record("[DEBUG: -- SSO ERR -- ]".$e->getMessage(), 'DEBUG');
            return $this->showError();
        }
        if(!$open){
            return $this->showError();
        }

        $access_token = !empty($open['access_token']) ? $open['access_token']:'';
        $state = I('state');

        $states = $this->decodeState($state);
        // 来自PC
        if (!empty($states['platform']) && $states['platform'] == 5){
            session('oss_login', ['from' => 'pc']);
        }

        return $this->login($channel, $open['openid'], $open['nickname'], $open['avatar'], $access_token , $open);
    }

    protected function decodeState($state)
    {
        $decoded = [];
        if (!$state) return;
        $group = explode('|', $state);
        foreach ($group as $value) {
            $temp = explode(':', $value);
            $decoded[$temp[0]] = $temp[1];
        }
        return $decoded;
    }

    public function qqlogin()
    {
        $channel = I('channel');
        $redirect_url = cookie('redirect_url') ?: 'Index/index';
        $sns = ThinkOauth::getInstance($channel);
        try {
            $extend = $sns->parseExtend(I(''));
            $open = $sns->getAccessToken($code, $extend);
        } catch (\Exception $e) {
            \Think\Log::record("[DEBUG: -- SSO ERR -- ]".$e->getMessage(), 'DEBUG');
         }
        if(!$open){
         }
        return $this->login($channel, $open['openid'], $open['nickname'], $open['avatar']);
        echo '<script type="text/javascript"
src="http://qzonestyle.gtimg.cn/qzone/openapi/qc_loader.js" charset="utf-8" data-callback="true"></script>';
exit;
    }

    public function login($channel = '', $openid = '', $nickname = '', $avatar = '', $access_token = '', $open = [])
    {
        session('home_user_auth', null); // 清除用户session
        cookie('token', null, 'prefix=login');
        if (!$openid || !$channel)
        {
            $this->redirect('/');
        }
        $extend['platform'] = 0;
        if (session('oss_login.from') == 'pc'){
            $extend['platform'] = 5;
        }
        $avatar && $extend['avatar'] = $avatar;

        if ($channel == 'weixin'){
            $sns = ThinkOauth::getInstance($channel);
            $openid = $sns->getUnionid($access_token, $openid);
        }

        do{
            try {
                $uid = event('User')->ssoLogin($channel, $openid, $nickname, $extend, $open);
            } catch(\Excetion $e) {
                usleep(200*1000);
                \Think\Log::record("[DB ERROR: -- SSO ERR -- ]".$e->getMessage(), 'ERROR');
            }
            $i++;
        }while (!$uid && $i < 5);

        if (!$uid) {
            return redirect(U('Sso/code', ['channel' => $channel, 'code' => $this->code]));
        }

        $Member = D('Member');
        $user = $Member->login($uid);
        event('Statis')->doLocalStatis('login', $extend['platform']);

        if (session('oss_login.from') == 'pc'){
            $res = event('User')->genToken($uid, '', 0, 5);
            $token = $res['data']['appToken'];
            session('oss_login', ['from' =>'pc', 'token' => $token]);
        }

        session('sso_channel', $channel);

        if (empty($user['nickname'])){
            cookie('sso_nickname', $nickname);
            cookie('sso_channel', $channel);
            cookie('sso_avatar', $avatar);

            // 添加登录类型，区分web登录和第三方登录
            session('_login_user_id', $uid);
            session('_login_type', 'sso');
 
            if (IS_AJAX){
                return $this->success('ok', U('User/nickname'));
            }
            return $this->redirect('User/nickname');
        }else{
            if (IS_AJAX){
                return $this->success('ok');
            }
            
            if (session('oss_login.from') == 'pc'){
                $redirect_url = U('User/loginreturn', ['appToken' => session('oss_login.token')]);
            }else{
                $redirect_url = cookie('redirect_url') ?: U('Index/index');
            }
            header("location: ". $redirect_url);
            return;
        }
    }

    public function showError()
    {
        $redirect_url = cookie('redirect_url') ?: U('user/login');
        return $this->redirect($redirect_url);
    }

}
